var util = require('../../libs/util.js');
var moment = require('../../libs/moment.min.js');
moment.locale('zh-cn');
var app = getApp();
Page({
  data: {
    hasData: false,
    middle_height: "100vh",
    delivery_data: [],
    path_data: [],
    tempState:'temp-off',
    hrState:'hr-off',
    speed:0,
    gps_address:'暂无实时车辆位置地址',
    delivery_item_form:false,
    next_point:false
  },
  onPullDownRefresh: function () {
    //wx.stopPullDownRefresh()
  },
  onReady: function (e) {
  },
  onLoad: function (e) {
    var that = this;
    wx.setNavigationBarTitle({ "title": app.appName+"--运单详情" });
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          middle_height: res.windowHeight - 90,
          detail_height: res.windowHeight - 40,
          windowWidth: res.windowWidth
        });
      }
    });
    this.setData({
      id:e.id,
      server:app.server
    })
    if (e.did) {
      this.setData({
        did: e.did
      })
    }
    this.loadData();
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/order/order?id='+this.data.id
    }
  },
  loadData: function () {
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    var id = that.data.id;
    wx.request({
      url: app.server + '/atapi/delivery/process/getDeliveryMonitorDetail',
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Cookie':app.globalData.cookie
      },
      data: {
        delivery: id
      },
      success: function (res) {
        console.log(res.data)
        wx.hideLoading();
        var shop_data = res.data.data[1], trace_data = res.data.data[2];
        var delivery_data = res.data.data[0][0];
        //console.log(shop_data)
        that.setData({
          delivery_data: delivery_data,
          iotbox: delivery_data.iot_box||'WX'+delivery_data.vehicle
        });
        if (trace_data.length>0){
          that.setData({
            hasData:true
          })
        }
        var distance_exception = {};
        if (res.data.success && shop_data.length > 0) {
          delivery_data.shop_number = 0;
          delivery_data.shop_receive = 0;
          delivery_data.wh_number = 0;
          delivery_data.wh_receive = 0;
          for (var i = 0; i < shop_data.length; i++) {
            var receive_time = shop_data[i].receive_time;
            if (receive_time && String(receive_time).length < 12) {
              receive_time = '2019-01-01 ' + receive_time;
            }
            shop_data[i].receive_time = receive_time ? moment(receive_time).format('HH:mm') : '__:__';
            var _rt = String(shop_data[i].shop_time).replace("0000-00-00", "2019-01-01");
            if (String(_rt).length < 12){
              _rt = '2019-01-01 ' + _rt;
            }
            if (shop_data[i].wh_time != null) {
              var _rt = String(shop_data[i].wh_time).replace("0000-00-00","2019-01-01");
              if (String(_rt).length < 12) {
                _rt = '2019-01-01 ' + _rt;
              }
            }
            if (_rt == '' || _rt == null || _rt == 'undefined'){
              _rt = '2019-01-01 00:00:00'
            }
            shop_data[i].req_receive_time = moment(_rt).format('HH:mm');
            if (shop_data[i].is_receive == '1') {
              if (shop_data[i].shop_id) {
                delivery_data.shop_receive++;
              }
              if (shop_data[i].wh_id) {
                delivery_data.wh_receive++;
              }
              shop_data[i].checked = true;
            } else {
              shop_data[i].checked = false;
            }
            //距离授权
            if (shop_data[i].distance_exception == 2){
              distance_exception = shop_data[i];
            }
            if (shop_data[i].shop_id){
              delivery_data.shop_number++;
            }
            if (shop_data[i].wh_id) {
              delivery_data.wh_number++;
            }
          }
          for (var i = 0; i < trace_data.length; i++) {
            trace_data[i].ADD_TIME = moment(trace_data[i].ADD_TIME).format('HH:mm');
          }
          delivery_data.delivery_mile = delivery_data.delivery_mile ? Number(delivery_data.delivery_mile/1000).toFixed(1) : 0;
          delivery_data.delivery_time = delivery_data.delivery_time ? Number(delivery_data.delivery_time).toFixed(2) : 0;
          delivery_data.path_name = String(delivery_data.path_name).substr(0, (that.data.windowWidth - 50)/12)

          var cy_image_list = []
          if(delivery_data.cy_image){
            cy_image_list = delivery_data.cy_image.split(',')
          }

          that.setData({
            delivery_data: delivery_data,
            delivery_mile: Number(delivery_data.delivery_mile).toFixed(1),
            delivery_time: Number(delivery_data.delivery_time).toFixed(2),
            total_duration: Number(delivery_data.total_duration).toFixed(2),
            total_mileage: Number(delivery_data.total_mileage).toFixed(1),
            shop_data: shop_data,
            trace_data: trace_data,
            distance_exception: distance_exception,
            cy_image_list:cy_image_list
          });

          //距离授权
          if (Object.getOwnPropertyNames(distance_exception).length > 0){
            that.setData({
              modalName: 'distanceException',
              distance_exception_text: '司机【'+delivery_data.driver_name + '】到达【' + (distance_exception.wh_name||distance_exception.name)+'】后，获取距离大于要求距离，申请临时无限制通过。请核查后再审核！'
            })
          }
          if (delivery_data.driver_status != "end") {
            // app.socket.on(that.data.iotbox, function (data) {
              
            //   //console.log(data)
            //   if (data.iotType == "NT") {// || data.iotType == "TP"
            //     that.setData({
            //       temperature: data.temperature,
            //       tempState: (Number(data.temperature) > Number(that.data.tpAlarm) ? 'temp-warn' : 'temp-on')
            //     });
            //   } else if (data.iotType == "HR") {
            //     that.setData({
            //       humidity: data.humidity,
            //       hrState: data.humidity ? 'hr-on' : 'hr-off'
            //     });
            //   }else if (data.iotType == "PS") {
            //     that.setData({
            //       speed: data.speed,
            //       latitude: data.latitude,
            //       longitude: data.longitude
            //     });
            //   };
            // });
          };
        };
      },
      fail: function (error) {
        wx.hideLoading();
        console.log(error);
      }
    });

    setTimeout(function(){
      if (that.data.longitude) {
        that.geocode(that.data.longitude, that.data.latitude);
        that.nextPointReachTime();
      }
    },3000);
    setInterval(function () {
      if (that.data.longitude) {
        that.geocode(that.data.longitude, that.data.latitude);
        that.nextPointReachTime();
      }
    }, 60000);
    
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  previewCyImage: function (e) {
    var that = this;
    var current = e.currentTarget.dataset.url
    wx.previewImage({
      current: current,
      urls: that.data.cy_image_list
    })
  },
  agreeDistanceException(e) {
    var that = this;
    wx.showModal({
      title: '温馨提示',
      content: '确认同意授权临时不限制距离吗？',
      success(res) {
        if (res.confirm) {
          util.postData("/atapi/delivery/process/agreeDistanceException", {
            state: 1,
            id: that.data.id,
            did: that.data.distance_exception.ID,
            point_name: that.data.distance_exception.wh_name || that.data.distance_exception.name,
            schedule_user: app.globalData.truename,
            distance_exception_distance: that.data.distance_exception.distance_exception_distance,
            CO_ID:app.globalData.CO_ID
          }, function (res) {
            if (res.data.success) {
              wx.showToast({
                title: '审核通过', icon: 'success', duration: 2000, success: function () { 
                  setTimeout(function () {
                    wx.navigateTo({
                      url: '/pages/order/order?id=' + that.data.id
                    })
                  },2000)
                }
              });
            } else {
              wx.showToast({ title: '审核失败', image: '/images/wrong.svg', duration: 2000 });
            }
          });
        }
      }
    })
    
  },
  nextPointReachTime: function(){
    var that = this;
    var shop_data = that.data.shop_data;
    for (var i = 0; i < shop_data.length; i++) {
      if (shop_data[i].is_receive == 0) {
        that.setData({
          next_point: shop_data[i].wh_name || shop_data[i].name,
          next_point_coord: shop_data[i].w_coord || shop_data[i].s_coord
        });
        var coord = String(shop_data[i].w_coord || shop_data[i].s_coord).split(",");
        util.getData("getDrivingPathOfCoord", { 
          lon: that.data.longitude, 
          lat: that.data.latitude, 
          nextLon: coord[1],
          nextLat: coord[0]
          }, function (res) {
          if (res.data.success) {
            var duration = res.data.data.duration/60;
            var _hour = Math.floor(duration/60);
            var _minute = Number(duration - _hour*60).toFixed(0);
            that.setData({
              nextPiontDistance: Number(res.data.data.distance/1000).toFixed(1),
              nextPiontDuration: _hour + '时' + _minute + '分',
            })
          }
        });
        return false;
      }
    }
  },
  geocode: function (longitude, latitude) {
    var that = this;
    util.getData("geocode", { longitude: longitude, latitude: latitude }, function (res) {
      if (res.data.success) {
        that.setData({
          gps_address: res.data.data
        })
      }
    });
  },
  showResult:function(e){
    var that = this;console.log(e)
    var id = e.currentTarget.id;
    var _type = e.currentTarget.dataset.type;
    var shop_data = that.data.shop_data, _shop_data = {};
    for (var i = 0; i < shop_data.length;i++){
      if (_type == 'shop' && shop_data[i].ID == id){
        _shop_data = shop_data[i];
        break;
      }
      if (_type == 'warehouse' && shop_data[i].wh_id == id) {
        _shop_data = shop_data[i];
        break;
      }
    }
    var _form_rule = [], form_rule = String(_shop_data.delivery_form_data).split(",");
    if (_shop_data.delivery_form_data != null) {
      for (var j in form_rule) {
        var _item = String(form_rule[j]).split("|");
        _form_rule.push({ "id": "FR" + j, "name": _item[0], "value": _item[1] });
      }
    }
    var deliveryImageList = [];
    var _deliveryImageList = String(_shop_data.delivery_scene_picture||"").split(",");
    for (var j in _deliveryImageList) {
      if (_deliveryImageList[j]){
        deliveryImageList.push(app.server + _deliveryImageList[j]);
      };
    }
    that.setData({
      delivery_item_form:true,
      form_rule: _form_rule,
      deliveryImageList: deliveryImageList
    });
  },
  delivery_item_form_close:function(){
    this.setData({
      delivery_item_form: false
    });
  },
  previewImage: function (e) {
    var current = e.target.dataset.src

    wx.previewImage({
      current: current,
      urls: this.data.deliveryImageList
    })
  },
  callDriver: function (e) {
    var phone = e.currentTarget.dataset.phone;
    if (phone){
      wx.makePhoneCall({
        phoneNumber: phone
      })
    }else{
      wx.showToast({
        title: "暂无号码",
        image: '/images/wrong.svg',
        duration: 2000
      });
    }
  },
  vehicleTrace: function (e) {
    // var id = e.currentTarget.id;
    // util.vehicleTrace(id);
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/report/pages/gps?id=' + id
    })
  },
  tpTrace: function(e) {
    var id = e.currentTarget.id;
    var iotbox = e.currentTarget.dataset.iotbox;
    wx.navigateTo({
      url: '/pages/report/pages/tp?id='+id+'&iotbox='+iotbox
    })
  },
  hrTrace: function (e) {
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/order/hr?id=' + id
    })
  },
  deliveryPicture:function(e){
    var delivery_picture = String(this.data.delivery_data.delivery_picture);
    if (delivery_picture.indexOf("http")>-1){
      wx.previewImage({
        urls: [delivery_picture]
      })
    }else{
      wx.showToast({
        title: "未有单据",
        image: '/images/wrong.svg',
        duration: 2000
      });
    }
  },
  driverLocation: function (e) {
    util.getData("getVehicleLocation", { 'iot_box': this.data.iotbox}, function (res, error) {
      console.log(res); console.log(error);
      if (error) {
        wx.showToast({
          title: "暂无车辆位置",
          image: '/images/wrong.svg',
          duration: 3000
        });
        return false;
      }
      if (res.data.success) {
        var gps = String(res.data.data).split(",");
        wx.openLocation({
          latitude: Number(gps[0]),
          longitude: Number(gps[1]),
          scale: 28
        })
      } else if (res.data.success == false) {
        wx.showToast({
          title: "暂无车辆位置",
          image: '/images/wrong.svg',
          duration: 3000
        });
      }
    });
  },
  deliveryTrace: function (e) {
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/vehicle/trace?id=' + id
    })
  },
  closePathDetail:function(){
    wx.navigateBack({
      delta: 1
    });
  },
  startSpeechRecognition: function (e) {
    var that = this;
    util.speechRecognition(function (data) {
      if (data) {
        var data = String(data).split("，")[0];
        that.AI(data);
      } else {
        wx.showToast({
          title: '识别失败',
          image: '/images/wrong.svg',
          duration: 2000,
          mask: true
        })
      }
    });
  },
  stopSpeechRecognition: function (e) {
    wx.stopRecord();
    wx.hideToast();
  },
  AI: function (text) {
    var that = this;
    wx.showToast({
      title: "搜索：" + text,
      icon: 'success',
      duration: 20000,
      mask: true
    });
    var delivery_data = that.data.delivery_data, shop_data = that.data.shop_data, isFind = false;
    for (var i = 0; i < delivery_data.length; i++) {
      if (String(delivery_data[i].path_name).indexOf(text) > -1
        || String(delivery_data[i].driver_name).indexOf(text) > -1
        || String(delivery_data[i].driver_phone).indexOf(text) > -1
        || String(delivery_data[i].plate).indexOf(text) > -1) {
        that.setMap(delivery_data[i].ID);
        isFind = true;
        wx.hideToast();
        break;
      }
    };
    if (!isFind) {
      for (var i = 0; i < shop_data.length; i++) {
        if (String(shop_data[i].name).indexOf(text) > -1) {
          that.setMap(shop_data[i].ID);
          isFind = true;
          wx.hideToast();
          break;
        }
      };
    }
    if (!isFind) {
      wx.showToast({
        title: "没有数据",
        image: '/images/wrong.svg',
        duration: 2000,
        mask: true
      });
    }
  },
  gotoPathNew: function () {
    wx.redirectTo({
      url: '/pages/index/deliveryForm?delivery=true'
    })
  },
  gotoHome: function () {
    wx.redirectTo({
      url: '/pages/shipper/shipper'
    })
  },
  gotoInfo: function () {
    wx.redirectTo({
      url: '/pages/shipper/shipperInfo'
    })
  },
  gotoCurrentOrder: function () {
    wx.redirectTo({
      url: '/pages/shipper/currentOrder'
    })
  },
  gotoHistoryOrder: function () {
    wx.redirectTo({
      url: '/pages/shipper/historyOrder'
    })
  }
})
